package com.sky.config;

import com.sky.properties.WeChatProperties;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PrivateKey;

@Configuration
public class HttpClientConfiguration {
    @Bean
    public CloseableHttpClient httpClient(WeChatProperties weChatProperties) throws Exception {
        PrivateKey merchantPrivateKey = PemUtil
                .loadPrivateKey(Files.newInputStream(Paths.get(weChatProperties.getPrivateKeyFilePath())));

        // 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3密钥）
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(weChatProperties.getMchid(), new PrivateKeySigner(weChatProperties.getMchSerialNo(), merchantPrivateKey)),
                weChatProperties.getApiV3Key().getBytes("utf-8"));

        // 初始化httpClient
       CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(weChatProperties.getMchid(), weChatProperties.getMchSerialNo(), merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
       return httpClient;
    }
}
